# 封装 三级商品分类
from apps.goods.models import GoodsChannel


def get_categories():

    # 1.1获取所有频道37个
    # 优化排序
    # channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    channels = GoodsChannel.objects.all()
    # 优化排序
    # categories = OrderedDict()
    categories = {}
    for channel in channels:
        #     1.2根据频道获取组id
        group_id = channel.group_id
        #     1.3判断 如果字典里面 有组id  不再生成新的字典
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}
            # 1.4 根据频道 获取 一级分类 category外键属性
            # 一级分类 需要 多加一个key-url--频道表
        cat1 = channel.category
        # 动态添加属性
        cat1.url = channel.url
        categories[group_id]['channels'].append(cat1)
        # 1.5 处理二级  三级 分类 cat1.subs.all()  cat2.subs.all()
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)
    return categories